<template>
  <div class="app-container">
    <!-- 列表模式 -->
    <div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:level:add']"
        >添加
        </el-button>
      </el-col>

    </el-row>

    <el-table v-loading="loading" :data="levelList">
      <el-table-column label="编码" align="center" prop="code"/>
      <el-table-column label="紧急程度" align="center" prop="name">
        <template slot-scope="scope">
          <span
            :style="{
              backgroundColor: scope.row.colorHex || '#409EFF',
              color: '#fff',
              padding: '4px 8px',
              borderRadius: '4px',
              fontSize: '12px'
            }"
          >
            {{ scope.row.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="是否启用" align="center" prop="enabled">
        <template slot-scope="scope">
          <div style="display:inline-flex;align-items:center;">
            <el-switch
              v-model="scope.row.enabled"
              :active-value="1"
              :inactive-value="0"
              @change="onToggleEnabled(scope.row,$event)"
            />
            <span style="margin-left:8px;color:#303133;">{{ scope.row.enabled===1?'启用':'禁用' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:level:edit']"
          >编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:level:remove']"
            style="color: #f56c6c;"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    </div>

    <!-- 弹窗：新增/编辑紧急程度 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="520px" append-to-body :close-on-click-modal="false" :show-close="false">
      <level-form v-if="dialogVisible" :mode="dialogMode" :code="editCode" :disable-enabled="false" @success="onFormSuccess" @close="dialogVisible=false" />
    </el-dialog>
  </div>
</template>

<script>
import {listLevel, getLevel, delLevel, addLevel, updateLevel} from "@/api/dict/level"
import LevelForm from './components/LevelForm.vue'
import { refreshDictionary } from '@/utils/dictionary'

export default {
  name: "Level",
  components: { LevelForm },
  computed: {},
  data() {
    return {
      loading: true,
      total: 0,
      levelList: [],
      queryParams: { pageNum: 1, pageSize: 9999 },
      dialogVisible:false,
      dialogMode:'create',
      editCode:'',
      currentEditingInUse:false,
      dialogTitle:'',
    }
  },
  async created() { await this.getList() },
  watch: {},
  methods: {
    /** 查询紧急程度列表 */
    async getList() {
      this.loading = true
      const response = await listLevel(this.queryParams)
      // 确保 enabled 为数字，并在缺省时默认启用，避免首屏抖动
      this.levelList = (response.rows || []).map(it => ({
        ...it,
        enabled: (it.enabled===undefined||it.enabled===null) ? 1 : ((it.enabled===1||it.enabled==='1'||it.enabled===true)?1:0)
      }))
      this.total = response.total
      this.loading = false
    },
    /** 新增按钮操作 */
    handleAdd() { this.dialogMode='create'; this.editCode=''; this.dialogVisible=true },
    /** 修改按钮操作 */
    handleUpdate(row) { this.dialogMode='edit'; this.editCode=row.code; this.dialogVisible=true },
    /** 删除按钮操作 */
    handleDelete(row) {
      const codes = row.code || this.ids
      this.$modal.confirm('是否确认删除紧急程度编号为"' + codes + '"的数据项？')
        .then(() => delLevel(codes))
        .then(() => { this.getList(); this.$modal.msgSuccess("删除成功") })
        .catch(err => { if (err && err.response && err.response.data && err.response.data.msg) { this.$modal.msgError({ message: err.response.data.msg, duration: 2000 }) } })
    },
    onFormSuccess(){ this.dialogVisible=false; this.getList() },
    // 切换启用状态（表格内直接修改）
    async onToggleEnabled(row, newVal) {
      const original = row.enabled
      row.enabled = newVal
      const payload = { code: row.code, enabled: Number(newVal) }
      try {
        await updateLevel(payload)
        this.$modal.msgSuccess({ message: '状态已更新', duration: 800 })
        // 刷新字典缓存，确保其他页面使用最新的数据
        await refreshDictionary('urgencyLevels')
      } catch (error) {
        row.enabled = original
        // 显示后端返回的具体错误信息
        const errorMsg = error.response?.data?.msg || '更新失败'
        this.$modal.msgError({ message: errorMsg, duration: 2000 })
      }
    }
  }
}
</script>
